package com.moshang.blog.controller.base;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.moshang.blog.core.annotation.SystemLog;
import com.moshang.blog.core.constant.Constants;
import com.moshang.blog.core.utils.BeanUtils;
import com.moshang.blog.core.utils.PageUtil;
import com.moshang.blog.core.utils.StringUtils;
import com.moshang.blog.core.utils.ToolUtil;
import com.moshang.blog.entity.*;
import com.moshang.blog.mapper.ThirdLoginUserMapper;
import com.moshang.blog.service.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * @program: blog
 * @description: ${description}
 * @author: moshang
 * @create: 2019-02-01 09:47
 **/
public class BaseController {
    @Autowired
    private ThirdLoginService thirdLoginService;
    @Autowired
    private WeiboService weiboService;
    @Resource
    private ThirdLoginUserMapper thirdLoginUserMapper;
    @Autowired
    private ThirdLoginUserService thirdLoginUserService;
    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Autowired
    private TbArticleInfoService tbArticleInfoService;
    @Autowired
    private TbMessageService tbMessageService;
    @Autowired
    private TbSortService tbSortService;
    @Autowired
    private SysDictService sysDictService;
    @Autowired
    private SysUsersService sysUsersService;
    @Autowired
    private SiteService siteService;


    /**
     * 页面跳转
     */
    public String redirect(String url)
    {
        return StringUtils.format("redirect:{}", url);
    }

    /**
     * qq登录
     */
    @RequestMapping("/qq/auth")
    @SystemLog("qq登录")
    public String qqAuth(@RequestParam("status") String status, @RequestParam(value = "articleId",required = false) String articleId, @RequestParam(value = "redirectUrl",required = false,defaultValue = "") String redirectUrl) {
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(articleId)){
            List<String> list=new ArrayList<>();
            list.add(status);
            list.add(articleId);
            status=String.join(",",list);
        }
        ThirdLogin thirdLogin = thirdLoginService.getInFo();
        if (StringUtils.isNotBlank(redirectUrl)){
            List<String> list=new ArrayList<>();
            list.add(status);
            list.add(redirectUrl);
            status=String.join(",",list);
        }
        StringBuilder url = new StringBuilder(thirdLogin.getQqAuthUrl())
                .append("?response_type=code")
                .append("&client_id=").append(thirdLogin.getQqAppId())
                .append("&redirect_uri=").append(thirdLogin.getQqRedictUrl())
                .append("&state=").append(status);
        return "redirect:" + url.toString();
    }
    /**
     * qq退出登录
     */
    @RequestMapping("/qqloginOut")
    @SystemLog("qq退出登录")
    public String loginOut(@RequestParam(value = "redirectUrl",required = false,defaultValue = "") String redirectUrl,Model model, HttpSession httpSession) {
        httpSession.removeAttribute("thirdLoginUser");
       if (StringUtils.isNotBlank(redirectUrl)){
           return "redirect:"+redirectUrl;
       }else {

           PageUtil<TbArticleInfo> pageUtil = new PageUtil<>();
           //查询所有置顶的文章
           QueryWrapper<TbArticleInfo> queryWrapper = new QueryWrapper<>();
           queryWrapper.eq("is_top", 1);
           queryWrapper.eq("status", 1);
           queryWrapper.eq("is_activited", 0);
           queryWrapper.orderByDesc("create_time");
           IPage<TbArticleInfo> articleInfoPage = tbArticleInfoService.page(new Page<>(1, 10), queryWrapper);
           pageUtil.setCount((int) articleInfoPage.getTotal());
           pageUtil.setData(articleInfoPage.getRecords());
           model.addAttribute("pageUtil", pageUtil);
           //查询最新推荐的五篇文章
           List<TbArticleInfo> isRecommends = tbArticleInfoService.findByIsRecommend();
           model.addAttribute("isRecommends", isRecommends);

           return "web/index";
       }
    }

    /**
     * qq登录授权回调
     *
     * @param code
     * @retu rn
     */
    @CrossOrigin
    @RequestMapping(value = "/qqCallback", method = RequestMethod.GET)
    public String qqCallback(String code, String state, Model model, HttpSession httpSession ) {
        List<String> states= Arrays.asList(state.split(","));
        String status="";
        String redirectUrl="";
        status=states.get(0);
        if (states.size()>1){
            redirectUrl=states.get(1);

        }
        //根据code获取ass_token
        Map<String, String> map = thirdLoginService.getTokenAsstoken(code);
        if (map.get("access_token") != null) {
            //使用Access Token来获取用户的OpenID
            Map<String, String> map1 = thirdLoginService.getOpenId(map.get("access_token"));
            //获取用户信息
            Map<String, String> map2 = thirdLoginService.getUserInfo(map.get("access_token"), map1.get("openid"));
            //保存到三方用户信息表中
            ThirdLoginUser thirdLoginUser = new ThirdLoginUser();
            SysUser sysUser = new SysUser();
            //根据openId和类型查询是否存在
            String loginType = "qq";
            String pw = ToolUtil.entryptPassword(Constants.DEFAULT_PASSWORD, Constants.DEFAULT_SALT).split(",")[0];
            ThirdLoginUser param = thirdLoginUserService.findBycondition(map1.get("openid"), loginType,Integer.parseInt(status));
            if (param != null) {
                param.setLastLoginTime(new Date());
                thirdLoginUserService.updateDate(param);
                BeanUtils.copyBeanProp(thirdLoginUser, param);
                if (Constants.BACK_LOGIN.equals(status)) {
                    sysUser = sysUsersService.findUserByThirdLoginId(param.getId());
                    sysUser.setLastLoginTime(new Date());
                    sysUsersService.updateById(sysUser);
                }
            } else {
//                thirdLoginUser.setThirdId(UUID.randomUUID().toString());
                thirdLoginUser.setAccessToken(map.get("access_token"));
                thirdLoginUser.setLoginType(loginType);
                thirdLoginUser.setOpenId(map1.get("openid"));
                thirdLoginUser.setNickName(map2.get("nickname"));
                thirdLoginUser.setAvatar(map2.get("figureurl_qq_1"));
                thirdLoginUser.setGender(map2.get("gender"));
                thirdLoginUser.setStatus(Integer.parseInt(status));
                thirdLoginUser.setLastLoginTime(new Date());
                thirdLoginUserMapper.insert(thirdLoginUser);
                if (Constants.BACK_LOGIN.equals(status)) {
                    //创建用户
                    //设置临时用户
                    sysUser.setThirdLoginId(thirdLoginUser.getId());
                    sysUser.setUserName(thirdLoginUser.getNickName());
                    sysUser.setRealName(thirdLoginUser.getNickName());
                    sysUser.setImage(thirdLoginUser.getAvatar());
                    sysUser.setPassword(pw);
                    sysUser.setSex(thirdLoginUser.getGender());
                    sysUser.setSalt(Constants.DEFAULT_SALT);
                    sysUser.setLastLoginTime(thirdLoginUser.getLastLoginTime());
                    sysUser.setIsActivited(0);
                    sysUser.setUpdateTime(new Date());
                    sysUser.setCreateTime(new Date());
                    sysUsersService.save(sysUser);
                    //设置角色为普通用户
                    SysUserRole sysUserRole = new SysUserRole();
                    sysUserRole.setRoleId(3);
                    sysUserRole.setUserId(sysUser.getId());
                    sysUserRoleService.save(sysUserRole);
                }
            }
            if (Constants.BACK_LOGIN.equals(status)) {
                Site site = siteService.getCurrentSite();
                model.addAttribute("site", site);
                model.addAttribute("user", sysUser);
                Subject user = SecurityUtils.getSubject();
                UsernamePasswordToken token = new UsernamePasswordToken(sysUser.getUserName(), Constants.DEFAULT_PASSWORD);
                user.login(token);
                if (user.isAuthenticated()) {
                    return "back/index";
                }
            } else {
                //前台登录
                // 将用户保存到session内
                if (thirdLoginUser!=null) {//判断不用管
                    httpSession.setAttribute("thirdLoginUser", thirdLoginUser);
                }
                    model.addAttribute("thirdLoginUser", thirdLoginUser);
                    PageUtil<TbArticleInfo> pageUtil = new PageUtil<>();
                    //查询所有置顶的文章
                    QueryWrapper<TbArticleInfo> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("is_top", 1);
                    queryWrapper.eq("status", 1);
                    queryWrapper.eq("is_activited", 0);
                    queryWrapper.orderByDesc("create_time");
                    IPage<TbArticleInfo> articleInfoPage = tbArticleInfoService.page(new Page<>(1, 10), queryWrapper);
                    pageUtil.setCount((int) articleInfoPage.getTotal());
                    pageUtil.setData(articleInfoPage.getRecords());
                    model.addAttribute("pageUtil", pageUtil);

                    //查询最新推荐的五篇文章
                    List<TbArticleInfo> isRecommends = tbArticleInfoService.findByIsRecommend();
                    model.addAttribute("isRecommends", isRecommends);
                    if (StringUtils.isNoneBlank(redirectUrl)){
                        return "redirect:" +redirectUrl;
                    }else {
                        return "web/index";
                    }

            }
        }
        return null;
    }

    /**
     * 微博登录
     */
    @RequestMapping("/weibo/auth")
    @SystemLog("微博登录")
    public String auth() {
        ThirdLogin thirdLogin = thirdLoginService.getInFo();
        String url = new StringBuilder(thirdLogin.getWeiboAuthUrl())
                .append("?client_id=").append(thirdLogin.getWeiboAppKey())
                .append("&redirect_uri=").append(thirdLogin.getWeiboRedictUrl())
                .append("&state=moko").toString();
        return "redirect:" + url;
    }

    /**
     * 登录授权回调
     *
     * @param code
     * @return
     */
    @RequestMapping(value = "/weiboCallback", method = RequestMethod.GET)
    public String callback(String code, Model model, HttpServletRequest request) {
        Map<String, String> map = weiboService.getUid(code);
        if (map.get("uid") != null && map.get("token") != null) {
            Map<String, String> map1 = weiboService.getInfo(map.get("uid"), map.get("token"));
            //保存到三方用户信息表中
            ThirdLoginUser thirdLoginUser = new ThirdLoginUser();
            SysUser sysUser = new SysUser();
            //根据openId和类型查询是否存在
            String loginType = "weibo";
            String pw = ToolUtil.entryptPassword(Constants.DEFAULT_PASSWORD, Constants.DEFAULT_SALT).split(",")[0];
            ThirdLoginUser param = thirdLoginUserService.findBycondition(map.get("uid"), loginType,1);
            if (param != null) {
                param.setLastLoginTime(new Date());
                thirdLoginUserService.updateDate(param);
                sysUser = sysUsersService.findUserByThirdLoginId(param.getId());
                sysUser.setLastLoginTime(new Date());
                sysUsersService.updateById(sysUser);
            } else {
//                thirdLoginUser.setThirdId(UUID.randomUUID().toString());
                thirdLoginUser.setAccessToken(map.get("token"));
                thirdLoginUser.setLoginType(loginType);
                thirdLoginUser.setOpenId(map1.get("idstr"));
                thirdLoginUser.setNickName(map1.get("name"));
                thirdLoginUser.setAvatar(map1.get("avatar_hd"));
                String gender = "m".equals(map1.get("gender")) ? "男" : ("f".equals(map1.get("gender")) ? "女" : "");
                thirdLoginUser.setGender(gender);
                thirdLoginUser.setLastLoginTime(new Date());
                thirdLoginUser.setStatus(1);
                thirdLoginUserMapper.insert(thirdLoginUser);
                //创建用户
                //设置临时用户
                sysUser.setThirdLoginId(thirdLoginUser.getId());
                sysUser.setUserName(thirdLoginUser.getNickName());
                sysUser.setRealName(thirdLoginUser.getNickName());
                sysUser.setImage(thirdLoginUser.getAvatar());
                sysUser.setPassword(pw);
                sysUser.setSex(thirdLoginUser.getGender());
                sysUser.setSalt(Constants.DEFAULT_SALT);
                sysUser.setLastLoginTime(thirdLoginUser.getLastLoginTime());
                sysUser.setIsActivited(0);
                sysUser.setUpdateTime(new Date());
                sysUser.setCreateTime(new Date());
                sysUsersService.save(sysUser);
                //设置角色为普通用户
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setRoleId(3);
                sysUserRole.setUserId(sysUser.getId());
                sysUserRoleService.save(sysUserRole);
            }
            Site site = siteService.getCurrentSite();
            model.addAttribute("site", site);
            model.addAttribute("user", sysUser);
            Subject user = SecurityUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(sysUser.getUserName(), Constants.DEFAULT_PASSWORD);
            user.login(token);
            if (user.isAuthenticated()) {
                return "back/index";
            }
        }
        return null;
    }

    /**
     * github回调
     *
     * @param code
     * @param request
     * @param response
     * @param model
     * @return
     * @throws Exception
     */
    @GetMapping("/githubCallback")
    public String auth(@RequestParam(value = "code") String code,
                       HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {
        ThirdLogin thirdLogin = thirdLoginService.getInFo();

        //1、根据code获取token,根据openId判断用户是否已经绑定过
        String accessToken = null;
        ThirdLoginUser thirdLoginUser = null;
        //根据openId和类型查询是否存在
        String loginType = "github";
        String pw = ToolUtil.entryptPassword(Constants.DEFAULT_PASSWORD, Constants.DEFAULT_SALT).split(",")[0];
        try {
            accessToken = thirdLoginUserService.getAccessToken(code, thirdLogin.getGithubClientId(), thirdLogin.getGithubClientSecret(), thirdLogin.getGithubRedictUrl());
        } catch (Exception e) {
            e.printStackTrace();
            return "back/login";
        }

        thirdLoginUser = thirdLoginUserService.getUserInfo(accessToken, null);
        SysUser sysUser = new SysUser();
        ThirdLoginUser param = thirdLoginUserService.findBycondition(thirdLoginUser.getOpenId(), loginType,1);
        if (param != null) {
            param.setLastLoginTime(new Date());
            thirdLoginUserService.updateDate(param);
            sysUser = sysUsersService.findUserByThirdLoginId(param.getId());
            sysUser.setLastLoginTime(new Date());
            sysUsersService.updateById(sysUser);
        } else {
//            thirdLoginUser.setThirdId(UUID.randomUUID().toString());
            thirdLoginUser.setAccessToken(accessToken);
            thirdLoginUser.setLoginType(loginType);
            thirdLoginUser.setOpenId(thirdLoginUser.getOpenId());
            thirdLoginUser.setLastLoginTime(new Date());
            thirdLoginUser.setStatus(1);
            thirdLoginUserMapper.insert(thirdLoginUser);
            //创建用户
            //设置临时用户
            sysUser.setThirdLoginId(thirdLoginUser.getId());
            sysUser.setUserName(thirdLoginUser.getNickName());
            sysUser.setRealName(thirdLoginUser.getNickName());
            sysUser.setImage(thirdLoginUser.getAvatar());
            sysUser.setPassword(pw);
            sysUser.setSex(thirdLoginUser.getGender());
            sysUser.setSalt(Constants.DEFAULT_SALT);
            sysUser.setIsActivited(0);
            sysUser.setLastLoginTime(thirdLoginUser.getLastLoginTime());

            sysUser.setUpdateTime(new Date());
            sysUser.setCreateTime(new Date());
            sysUsersService.save(sysUser);
            //设置角色为普通用户
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setRoleId(3);
            sysUserRole.setUserId(sysUser.getId());
            sysUserRoleService.save(sysUserRole);
        }
        Site site = siteService.getCurrentSite();
        model.addAttribute("site", site);
        model.addAttribute("user", sysUser);
        Subject user = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(sysUser.getUserName(), Constants.DEFAULT_PASSWORD);
        user.login(token);
        if (user.isAuthenticated()) {
            return "back/index";
        }
        return null;
    }
    /**
     * 微博登录
     */
    @RequestMapping("/alipay/auth")
    @SystemLog("支付宝登录")
    public String alipayAuth() {
        ThirdLogin thirdLogin = thirdLoginService.getInFo();
        StringBuilder url = new StringBuilder(thirdLogin.getAliAuthUrl())
                .append("?app_id=").append(thirdLogin.getAliAppId())
                .append("&scope=auth_user")
                .append("&redirect_uri=").append(thirdLogin.getAliRedictUrl())
                .append("&state=1");
        return "redirect:" + url;
    }
    /**
     * 登录授权回调
     *
     * @param code
     * @return
     */
    @RequestMapping(value = "/alipayCallback", method = RequestMethod.GET)
    public String alipayCallback(@RequestParam(value = "auth_code") String code, Model model, HttpServletRequest request) {
        String accessToken = thirdLoginService.getAliAccessToken(code);
        if (accessToken!= null ) {

        }
        return null;
    }
    /**
     * 用户退出
     */
    @RequestMapping("/logout")
    public String logout() {
        Subject currentUser = SecurityUtils.getSubject();
        currentUser.logout();
        return "back/login/login";

    }

    /**
     *
     * @return
     */
    protected List<TbSort> getSorts() {
        List<TbSort> sortList=tbSortService.getSorts();
        return sortList;
    }
    /**
     *
     * @return
     */
    protected List<SysDict> getLabels() {
        List<SysDict> labelList=sysDictService.findByCondition("文章标签");
        return labelList;
    }
}
